<template>
  <div id="app">
    <h1>📝 待办事项 TodoList</h1>
    <TodoInput @add="addTodo" />
    <TodoFilters @filter-change="filter = $event" />
    <p v-if="filteredTodos.length === 0" class="empty-tip">这里什么都没有呢～快去添加吧！(｡･ω･｡)</p>
    <TodoList :todos="filteredTodos" @delete="deleteTodo" @save="saveTodos" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import TodoInput from './components/TodoInput.vue'
import TodoFilters from './components/TodoFilters.vue'
import TodoList from './components/TodoList.vue'

// 移除未使用的 newTodo
// const newTodo = ref('')

// 明确 todos 的类型
const todos = ref<{ id: number; text: string; done: boolean }[]>([])
const filter = ref('all')  // 筛选状态

// localStorage 键名
const STORAGE_KEY = 'vue-todolist'

// 从 localStorage 加载数据
function loadTodos() {
  const storedTodos = localStorage.getItem(STORAGE_KEY)
  if (storedTodos) {
    todos.value = JSON.parse(storedTodos)
  }
}

// 保存数据到 localStorage
function saveTodos() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(todos.value))
}

// 添加任务
function addTodo(text: string) {
  todos.value.push({ id: Date.now(), text, done: false })
  saveTodos()
}

// 删除任务
function deleteTodo(id: number) {
  todos.value = todos.value.filter(todo => todo.id !== id)
  saveTodos()
}

// 计算属性：根据筛选状态过滤后的列表
const filteredTodos = computed(() => {
  if (filter.value === 'active') {
    return todos.value.filter(todo => !todo.done)
  } else if (filter.value === 'completed') {
    return todos.value.filter(todo => todo.done)
  }
  return todos.value
})

// 监听 todos 变化自动保存
watch(todos, () => {
  saveTodos()
}, { deep: true })

// 生命周期 mounted
onMounted(() => {
  loadTodos()
  console.log('萌萌TodoList已加载～ฅ^•ﻌ•^ฅ')
})
</script>

<style scoped>
/* 背景色和字体 */
body {
  margin: 0;
  background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
  font-family: 'Comic Sans MS', 'Chalkboard', cursive;
  min-height: 100vh;
}

/* 中心卡片 */
#app {
  max-width: 600px;
  margin: 50px auto;
  background: white;
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 16px rgba(0,0,0,0.2);
  text-align: center;
}

h1 {
  color: #ff6ec7;
  margin-bottom: 20px;
  font-weight: bold;
}

/* 空提示 */
.empty-tip {
  color: #888;
  margin: 20px 0;
}

/* 动画效果 */
.list-enter-active, .list-leave-active {
  transition: all 0.4s;
}

.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

@media (max-width: 640px) {
  #app {
    margin: 20px;
    padding: 15px;
  }
}
</style>